package com.spring.mvc.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.SecureRandom;
import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

/**
 * description:
 * @author leo
 * @version Version 1.0
 * @date   2005-10-18
 */
public class Encryptor {
	
	/**
	 * 根据指定文件获取KEY
	 * @param keyPath
	 * @return
	 * @throws Exception
	 */
	private static byte[] getKey(String keyPath) throws Exception {
		File pubKey = new File(keyPath);
		InputStream is = new FileInputStream(pubKey);
		byte[] rawKeyData = new byte[(int) pubKey.length()];
		is.read(rawKeyData, 0, (int) pubKey.length());
		return rawKeyData;
	}

	/**
	 * 根据给定key解密msg
	 * @param msg
	 * @param keyPath
	 * @return
	 * @throws Exception
	 */
	public static byte[] encryptMsg(byte[] msg,String keyPath) throws Exception {
		// get a DES private key
		byte[] keyAsBytes = getKey(keyPath);
		KeySpec keySpec = new DESKeySpec(keyAsBytes);
		Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey key = keyFactory.generateSecret(keySpec);
		cipher.init(Cipher.ENCRYPT_MODE, key);
		byte[] cleartext = msg;
		byte[] ciphertext = cipher.doFinal(cleartext);

		return ciphertext;
		//		return msg;
	}

	public static byte[] decryptMsg(byte[] msg,String keyPath) throws Exception {
		byte[] keyAsBytes = getKey(keyPath);
		
		SecureRandom sr = new SecureRandom();
		DESKeySpec dks = new DESKeySpec(keyAsBytes);
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey Keykey = keyFactory.generateSecret(dks);
		Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, Keykey, sr);
		byte decryptedData[] = cipher.doFinal(msg);
		return decryptedData;
	}
	
}
